package com.forage.exp.filter;

import com.forage.exp.constant.GlobalErrorEnum;
import com.forage.exp.constant.ResponseStatusEnum;
import com.forage.exp.po.GlobalException;
import com.forage.exp.po.UserAuthority;
import com.forage.exp.utils.JwtUtils;
import com.forage.exp.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import top.iceclean.logtrace.annotation.EnableLogTrace;
import top.iceclean.logtrace.bean.Logger;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author : George
 * @date : 2022-05-3
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private Logger logTrace;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");  //提取token
        if (!StringUtils.hasText(token)) {
            //如果token为空需要放行，因为在访问security的匿名接口时过滤器同样起作用，而此时token值为空
            filterChain.doFilter(request, response);
            return;
        }

        //解析token
        String userId;
        try {
            userId = JwtUtils.parseJWT(token).getSubject();
        } catch (Exception e) {
            resolver.resolveException(request,response,
                    null,new GlobalException(GlobalErrorEnum.AUTHENTICATION_EXCEPTION,"JWT解析失败"));
            return;
        }

        //校验用户信息
        String redisKey = "login:" + userId;
        UserAuthority userAuthority = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(userAuthority)){
            resolver.resolveException(request,response,
                    null,new GlobalException(GlobalErrorEnum.AUTHENTICATION_EXCEPTION,"JWT对应用户不存在"));
            return;
        }

        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userAuthority,null, userAuthority.getAuthorities());
        //存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        log.info("封装用户 {} 权限：{}", userAuthority.getUser().getUserAccount(), userAuthority.getAuthorities().toString());

        //放行
        filterChain.doFilter(request, response);
    }
}
